var gData = [ ]; //会另外从服务器获取
var PREDICT_COUNT = 6;

/**
 * 画图函数
 */
function createChart(toSelector, year, seriesData) {
	var chart = new Highcharts.Chart({
		chart: {
			renderTo: toSelector,
			marginTop: 30,
			marginRight: 50,
			spacingLeft: 30,
			spacingBottom: 25,
            height: 150,
		},
		title: { text: year },
		xAxis: {
			plotLines: [{ width: 1, color: "#808080" }],
			tickInterval: 1,
			labels: {
                x: 6,
				formatter: function() { 
                    var data = seriesData[0].data[this.value];
                    return data ? data.label : null; 
                },
			}
		},
		yAxis: [{
			title: { text: 'Days', rotation: 270 },
			tickInterval: 1,
			opposite: true,
			plotLines: [{ value: 0, width: 1, color: '#808080' }]
		}],
		tooltip: {
			formatter: function() {
				return '<b>' + this.series.name + '/' + this.point.label + '</b><br/><span>' + this.y + ' Days' + '</span>';
			}
		},
		legend: { enabled: false },
		series: seriesData,
        credits: { enabled: false }
	});//chart = new Highcharts.Chart({
}// function createChart()

// 文档加载完毕自动创建图形
$(document).ready(function() {
	// 根据数据量调整图的宽度，并自动滚动到最右边
	$('#container').html('Loading data...');
	//getData('http://git.oschina.net/lt123345/daily/raw/master/somewhat/dates.jsonp');
	getData('dates.jsonp');
});//$(document).ready(function() {

// 请求数据
function getData(url) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	document.head.appendChild(script);
}

// 数据到来之后会被调用到
function gotData(data) {
	gData = data;
    addPredictData();
    var seriesArr = parseGDataToSeriesData();
    $('#container').html('');
    for(var i=seriesArr.length-1; i>=0; i--) {
        var id = 'year'+seriesArr[i].name;
        var obj = $('<div class="chart" id="'+id+'"></div>').appendTo('#container');
        createChart(id, seriesArr[i].name, [seriesArr[i], getAvgSeries(seriesArr[i])]);
    }
}

// 自动添加预测以后N次的时间
function addPredictData() {
    if (!gData || gData.length == 0) return;
    var lastDate = new Date(gData[gData.length-1]);
    for(var i=0; i<PREDICT_COUNT; i++) {
        var nextDate = new Date(lastDate.getTime() + 28*24*60*60*1000);
        gData.push(nextDate.getFullYear()+'/'+(nextDate.getMonth()+1)+'/'+nextDate.getDate());
        lastDate = nextDate;
    }
}

function getAvgSeries(series) {
    var avgSeries = {
        name:'平均', 
        marker: { enabled: false },
        color: '#a00',
        lineWidth: 1,
        data:[]
    };

    var total = 0;
    Highcharts.each(series.data, function(d) { total+=d.y; });
    var avg = Math.round(total / series.data.length * 100) / 100; //保留两位小数
    for(var i=0; i<13; i++) {
        avgSeries.data.push({y:avg, label:'平均值'});
    }
    return avgSeries;
}

/**
 * 计算所有日期相差的天数，返回天数数组
 * 最后一条记录是预测日期，所以将其标为不同的颜色
 */
function parseGDataToSeriesData() {
	var totalDays = 0;

    // 给每一个年份建一个series
    var seriesMap = {};
	for(var i=1; i<gData.length; i++) {
        var year = gData[i].substr(0, 4);
        if(!seriesMap[year]) {
            seriesMap[year] = {
                name: year, 
                dataLabels: { 
                    enabled: true,
                    color: '#fff'
                },
                data:[]
            };
        }
		var dayCount = diffDays(gData[i-1], gData[i]);
        lastDayCount = dayCount;
        var data ={
            y: dayCount,
            label: gData[i].substr(5),
        };
        // 修改最后预测点的颜色
        if (i >= gData.length - PREDICT_COUNT) {
            data.marker = { fillColor: '#3e0' };
        } else {
            totalDays += dayCount;
        }
        seriesMap[year].data.push(data);
    }

    // 计算平均天数
	var avgDays = totalDays / (gData.length - PREDICT_COUNT - 1);
	avgDays = Math.round(avgDays * 100) / 100; //保留小数点后两位
	$('#avgDays').html(avgDays);

    // Map -> Array
    var seriesArr = [];
    for(var year in seriesMap) {
        seriesArr.push(seriesMap[year]);
    }
    return seriesArr;
}

/**
 * 求两个日期相差的天数
 * 当date1大于date2时，返回正值
 * @param date1 string 日期1
 * @param date2 string 日期2
 * @return 相差的天数
 */
function diffDays(date1, date2) {
	var d1 = Date.parse(date1);
	var d2 = Date.parse(date2);
	var diff = d2 - d1;
	return diff / (1000 * 3600 * 24);
}
